package com.repro.lib_base.bases.fragment

import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.repro.lib_base.bases.interfaces.IActivityHandler


abstract class FinalFragment : Fragment(), IActivityHandler {
    protected var rooView: View? = null
    private lateinit var mInflater: LayoutInflater

    /**
     * 合并外部数据和内部参数
     */
    override fun setArguments(args: Bundle?) {
        var bundle = arguments
        if (bundle == null) {
            bundle = Bundle()
        }
        if (args != null) {
            bundle.putAll(args)
        }
        super.setArguments(bundle)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mInflater = inflater
        rooView = initState(onFragmentCreateStart())
        initData(arguments)
        initView(rootView = rooView)
        setViewData(savedInstanceState)
        onFragmentCreateEnd()
        return rooView
    }

    /**
     * 初始化数据
     *
     * @param arguments
     */
    protected abstract fun initData(arguments: Bundle?)

    protected open fun onFragmentCreateStart(): View? {
        return rooView
    }

    /**
     * 像根布局添加状态state布局
     */
    protected open fun initState(view: View?): View? {
        return view
    }

    /**
     * 初始化view
     *
     * @param rootView
     */
    protected abstract fun initView(rootView: View?)

    /**
     * 初始化view相关联的数据
     */
    protected abstract fun setViewData(savedInstanceState: Bundle?)

    protected open fun onFragmentCreateEnd() {}

    fun getRootView(): View? {
        return rooView
    }

    /**
     * 返回键处理
     *
     * @return true：表示此fragment消化了返回键 false：表示没有消化返回键，交给activity处理
     */
    open fun onBackPressed(): Boolean {
        return false
    }


    /**
     * 在Fragment中创建使用ViewModel:
     * 具体也可以参考@see VMExt.kt 扩展类
     */
    override fun <T : ViewModel> getViewModel(mClass: Class<T>): T {
        return ViewModelProvider(this).get(mClass)
    }

    override fun getLayInflate(): LayoutInflater {
        return mInflater
    }

    override fun isDestroyed(): Boolean {
        return isDetached
    }

    override fun getActivityContext(): Activity {
        return requireActivity()
    }

}

